package com.atguigu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.GmallConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.sql.Connection;
import java.util.List;

public class DimUtil {

    public static JSONObject getDimInfo(Jedis jedis, Connection connection, String tableName, String key) throws Exception {

        //查询Redis中的数据
        String redisKey = "DIM:" + tableName + ":" + key;
        String dimInfoJsonStr = jedis.get(redisKey);
        if (dimInfoJsonStr != null) {
            jedis.expire(redisKey, 24 * 60 * 60);
            return JSON.parseObject(dimInfoJsonStr);
        }

        //拼接SQL语句  select * from db.tn where id = '123'
        String querySql = "select * from " + GmallConfig.HBASE_SCHEMA + "." + tableName + " where id = '" + key + "'";

        //查询Phoenix
        List<JSONObject> list = PhoenixUtil.query(connection, querySql, JSONObject.class, false);

        //将从Phoenix查询到的结果写入Redis
        JSONObject dimInfo = list.get(0);

        //jedis.setex(redisKey, 24 * 60 * 60, dimInfo.toJSONString());
        jedis.set(redisKey, dimInfo.toJSONString());
        jedis.expire(redisKey, 24 * 60 * 60);

        //返回结果数据
        return dimInfo;
    }

    public static void delRedisDimInfo(Jedis jedis, String tableName, String key) {
        String redisKey = "DIM:" + tableName + ":" + key;
        jedis.del(redisKey);
    }

    public static void main(String[] args) throws Exception {

        DruidDataSource dataSource = DruidDSUtil.createDataSource();
        JedisPool jedisPool = JedisPoolUtil.getJedisPool();

        long start = System.currentTimeMillis();
        DruidPooledConnection connection = dataSource.getConnection();
        Jedis jedis = jedisPool.getResource();
        System.out.println(getDimInfo(jedis, connection, "DIM_BASE_TRADEMARK", "12")); //149  159  147    150
        connection.close();
        jedis.close();
        long end = System.currentTimeMillis();

        DruidPooledConnection connection2 = dataSource.getConnection();
        Jedis jedis2 = jedisPool.getResource();
        System.out.println(getDimInfo(jedis2, connection2, "DIM_BASE_TRADEMARK", "12")); //8    8    9     10   1 1 1 1
        jedis2.close();
        connection2.close();
        long end2 = System.currentTimeMillis();

        System.out.println(end - start);
        System.out.println(end2 - end);

        dataSource.close();

    }

}
